using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using BirthdayReminder.Entities;
using BirthdayReminder.Business;

/// <summary>
/// Summary description for InlineService
/// </summary>
public class InlineService : IHttpHandler
{

    #region Variables
    Newtonsoft.Json.JsonSerializer js = new Newtonsoft.Json.JsonSerializer();
    #endregion

    public InlineService()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    bool IHttpHandler.IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
        context.Response.Clear();

        string action = context.Request.Params["action"];
        switch (action)
        {
            case "sendgift":
                SendGift(context);
                break;
            case "getallgift":
                GetAllGift(context);
                break;
            case "CheckExist":
                CheckExist(context);
                break;
            default:
            {
                Register(context);
                break;
            }
        }

        context.Response.Flush();
        context.Response.End();
    }

    private void SendGift(HttpContext context)
    {
        int senderId = (int)context.Cache["userId"];
        string receiverIds = context.Request.Params["receiverId"];
        string giftIds = context.Request.Params["gift"];
        string message = context.Request.Params["message"];

        if (string.IsNullOrEmpty(receiverIds) ||
            string.IsNullOrEmpty(giftIds) ||
            string.IsNullOrEmpty(message)
            )
        {
            context.Response.Write("{error:true,msg:'Invalid data'}");
            return;
        }

        string[] receiverItems = receiverIds.Split(',');
        string[] giftItems = giftIds.Split(',');
        for (int index = 0; index < receiverItems.Length; index++)
        {
            for (int index1 = 0; index1 < giftItems.Length; index1++)
            {
                int receiverId = int.Parse(receiverItems[index]);
                int giftid = int.Parse(giftItems[index1]);

                Present present = new Present();
                present.SenderId = senderId;
                present.GiftId = giftid;
                present.ReceiverId = receiverId;
                present.Message = message;
                present.CreationDate = DateTime.Now;
                present.Amount = 1;

                PresentService.CreatePresent(present);
            }
        }

        context.Response.Write("{error:false, msg:'Gift was sent successful'}");
    }
    #region
    private void GetAllGift(HttpContext context)
    {
        try
        {
            GiftCollection gifts = GiftService.GetGiftList(GiftColumns.Name, Pyco.Data.OrderDirection.ASC);
            js.Serialize(context.Response.Output, gifts);
        }
        catch (Exception ex)
        {
            context.Response.Write("{error:true,msg:'Exception while process data'}");
        }
    }
    private void CheckExist(HttpContext context)
    {
        try
        {
            int userId = int.Parse(context.Request.Params["userId"]);
            User  user= UserService.GetUser(userId);
            if(user==null)
            {
                context.Response.Write("{isExist:false}");
                return;
            }
            context.Cache["userId"] = userId;

            //context.Session["userid"] = userId;

            js.Serialize(context.Response.Output, user);
        }
        catch (Exception ex)
        {
            context.Response.Write("{error:true,msg:'Exception while process data:" + ex.ToString() + "'}");
        }
    }
    private void Register(HttpContext context)
    {
        try
        {
            string email = context.Request.Params["email"];
            int userId = int.Parse(context.Request.Params["userid"]);
            if (!StringHelper.IsMatch(email, AppConstant.EMAIL_FORMAT))
            {
                context.Response.Write("{error:true,msg:'Invalid email'}");
                return;
            }
            User usr= UserService.GetUser(userId);
            if (usr != null)
            {
                context.Response.Write("{error;true,msg:'This use is already exist in the system'}");
                return;
            }
            
            usr = new User();
            usr.UserId = userId;
            usr.Email = email;
            usr.CreationDate = DateTime.Now;

            UserService.CreateUser(usr);
            js.Serialize(context.Response.Output, usr);
        }
        catch (Exception ex)
        {
            context.Response.Write("{error:true,msg:'Exception while process data'}");
        }

    }
    #endregion
}
